import React, { useState, useRef, useEffect } from 'react';
import { Image, message, Button,Modal,Divider} from 'antd';
import { PlusOutlined ,ExclamationCircleOutlined} from '@ant-design/icons';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import { queryDeviceType, updateDeviceType, addDeviceType,removeDeviceType } from '@/services/devicetype';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
const { confirm } = Modal;

import { Link  ,useModel} from 'umi';


/**
 * 添加节点
 * @param fields
 */
 const handleAdd = async (fields: any) => {
  const hide = message.loading('正在添加');
  try {
    await addDeviceType(fields);
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: any) => {
  const hide = message.loading('正在保存');
  try {
    await updateDeviceType(fields);
    hide();
    message.success('保存成功');
    return true;
  } catch (error) {
    hide();
    message.error('保存失败请重试！');
    return false;
  }
};



const definition: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [formValues, setFormValues] = useState({});


  const columns: ProColumns[] = [
    {
      title: '类型id',
      dataIndex: 'typeId',
      hideInSearch: true,
    },
    {
      title: '设备类型',
      dataIndex: 'typeName',
    },
    {
      title: '设备类型描述',
      dataIndex: 'typeDescription',
    },
    {
      title: '表名',
      dataIndex: 'tableName',
    },

    {
      title: '图标',
      dataIndex: 'typeImg',
      hideInSearch: true,
      renderText: (icon: string) => {
        if (icon) {
          return <Image src={"/img/"+icon} width={40} height={40}/>;
        }
        return icon;
      },
    },

    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            onClick={async () => {
              handleUpdateModalVisible(true);
              setFormValues(record);
            }}
          >
            编辑
          </a> 
          <Divider type="vertical" />
          <Link  to={{pathname:`/monitoring/design/${record.typeId}`,state:{deviceType:record}}}  > 设计</Link>
          <Divider type="vertical" />
          <Link  to={{pathname:`/monitoring/designDetails/${record.typeId}`,state:{deviceType:record}}}  > 预览</Link>
        
          <Divider type="vertical" />
          <a onClick={async () => {remove(record)}} >删除</a>

        </>
      ),
    },
  ];


//删除单个
const toremove = async (typeId: number) => {
  const hide = message.loading('正在删除');
  try {
    await removeDeviceType({typeId});
    hide();
    message.success('删除成功，正在刷新！');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败请重试！');
    return false;
  }
};


const remove = async (fields: any) => {
console.log(fields)
  if(fields.hasDevice!=null){
    message.error('当前类型下有添加的设备，请先删除设备！');
    return ;
  }

  confirm({
    title: '您确定要删除吗?',
    icon: <ExclamationCircleOutlined />,
    async onOk() {
      await toremove(fields.typeId);
      actionRef.current?.reload();
    },
    onCancel() {
      console.log('Cancel');
    },
  });

 
};





  return (
    <>
      <ProTable
        headerTitle=""
        actionRef={actionRef}
        rowKey="typeId"
        options={false}
        toolBarRender={(action, { selectedRows }) => [
          <Button icon={<PlusOutlined />} type="primary" onClick={() => handleModalVisible(true)}>
            新增
          </Button>
        ]}
        request={(params) => queryDeviceType(params)}
        columns={columns}
        search={{
          labelWidth: 'auto',
        }}
        pagination={{
          defaultCurrent: 1,
          defaultPageSize: 10,
        }}
      />
      <CreateForm
        onSubmit={async (value) => {
          const success = await handleAdd(value);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              setFormValues({});
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
      />
      {formValues && Object.keys(formValues).length ? (
        <UpdateForm
          onSubmit={async (value) => {
            const success = await handleUpdate(value);
            if (success) {
              handleModalVisible(false);
              setFormValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          values={formValues}
        />
      ) : null}
    </>
  );
};

export default definition;